package com.bw.message.model

import android.util.Log
import com.bw.message.entity.MessageData
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import javax.inject.Inject

class WebSocketManager @Inject constructor(
    private val okHttpClient: OkHttpClient // 确保这个参数能被注入
){
    var webSocket: WebSocket? = null
    private val client = OkHttpClient()
    private var messageListener: ((List<MessageData>) -> Unit)? = null

    fun connect(url: String, accessId: String, userId: Int) {
        val request = Request.Builder()
            .url("$url?accessId=$accessId&userId=$userId")
            .build()

        webSocket = client.newWebSocket(request, object : WebSocketListener() {
            override fun onOpen(webSocket: WebSocket, response: Response) {
                Log.d("WebSocket", "连接已建立")
            }

            override fun onMessage(webSocket: WebSocket, text: String) {
                Log.d("WebSocket", "收到消息: $text")
                // 这里解析消息并通知监听器
                try {
                    val messages = parseMessages(text) // 需要实现parseMessages方法
                    messageListener?.invoke(messages)
                } catch (e: Exception) {
                    Log.e("WebSocket", "消息解析错误", e)
                }
            }

            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                Log.d("WebSocket", "连接关闭: $reason")
            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                Log.e("WebSocket", "连接失败${t.message}")
            }
        })
    }

    fun setMessageListener(listener: (List<MessageData>) -> Unit) {
        this.messageListener = listener
    }

    fun disconnect() {
        webSocket?.close(1000, "用户主动断开")
        client.dispatcher.executorService.shutdown()
    }

    private fun parseMessages(json: String): List<MessageData> {
        // 使用Gson或其他JSON库解析消息
        // 这里需要根据您的实际消息格式实现
        return emptyList()
    }
}